//
//  SJEditAudioViewController.m
//  WSL
//
//  Created by CJ on 2017/12/7.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJEditAudioViewController.h"
#import "SJModifyMediaApi.h"
#import "SJAddWHCell.h"
#import "SJAddItem.h"
#import "SJWordItem.h"
#import <ZLPhotoBrowser/ZLPhotoActionSheet.h>
#import <ZLPhotoBrowser/ZLPhotoConfiguration.h>
#import <Qiniu/QiniuSDK.h>
#import "SJGetUpTokenApi.h"
#import "SJExtraItem.h"

@interface SJEditAudioViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *navigationBarView; // 背景
@property (nonatomic, strong) UIScrollView *containView;
@property (nonatomic, strong) UIView *headerContainView;
@property (nonatomic, strong) UIView *inputBGView;
@property (nonatomic, strong) UITextField *titleTextView;
@property (nonatomic, strong) UIView *titleBGView;
@property (nonatomic, strong) UIButton *cameraButton;

@property (nonatomic, strong) UIImageView *picImageView;
@property (nonatomic, strong) UIButton *deleteButton;

@property (nonatomic, strong) UIImage *uploadImage;
@property (nonatomic, strong) QNUploadManager *upManager;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, copy) NSString *selectedWidth;
@property (nonatomic, copy) NSString *selectedHeight;

@property (strong, nonatomic) UIButton *cpButton;
@property (nonatomic, copy) NSString *allowCopy; // 1 不允许, 2 允许

@end

@implementation SJEditAudioViewController


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}

- (void)dealloc {
    SJLogFunc;
    [self removeObserver:self forKeyPath:@"selectedHeight" context:nil];
    [self removeObserver:self forKeyPath:@"selectedWidth" context:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupUI];
    //    [self.titleTextView becomeFirstResponder];
    
    [self addObserver:self forKeyPath:@"selectedWidth" options:NSKeyValueObservingOptionNew context:nil];
    [self addObserver:self forKeyPath:@"selectedHeight" options:NSKeyValueObservingOptionNew context:nil];
    
    [self configData];
    [self filterData];
}


- (void)configData {
    
    SJExtraItem *extraItem = [SJExtraItem modelWithJSON:self.item.extra];
    self.allowCopy = self.item.can_fav;
    if ([self.allowCopy isEqualToString:@"2"]) { // 允许复制
        _cpButton.selected = YES;
    } else {
        _cpButton.selected = NO;
    }
    
    self.titleTextView.text = extraItem.t;
    
    self.selectedHeight = self.item.h;
    self.selectedWidth = self.item.w;
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJImgURL, extraItem.cover];
    
    [self.picImageView setImageWithURL:[NSURL URLWithString:urlString] placeholder:nil options:YYWebImageOptionProgressiveBlur | YYWebImageOptionShowNetworkActivity | YYWebImageOptionSetImageWithFadeAnimation completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
        
        //        weakSelf.uploadImage = image;
    }];
    
}

- (void)filterData {
    
    SJAddItem *item_0 = self.dataArray[0];
    SJAddItem *item_1 = self.dataArray[1];
    
    for (NSMutableDictionary *dict in self.optionArray) {
        
        if ([dict[@"h"] isEqualToString:@"2"] && [dict[@"w"] isEqualToString:@"2"]) {  // 1:1
            item_0.state = @"1";
            if ([dict[@"w"] isEqualToString:self.selectedWidth] && [dict[@"h"] isEqualToString:self.selectedHeight]) {
                item_0.state = @"2";
            }
            break;
        } else {
            item_0.state = @"0";
        }
    }
    
    for (NSMutableDictionary *dict in self.optionArray) {
        
        if ([dict[@"h"] isEqualToString:@"4"] && [dict[@"w"] isEqualToString:@"4"]) {  // 2:2
            item_1.state = @"1";
            if ([dict[@"w"] isEqualToString:self.selectedWidth] && [dict[@"h"] isEqualToString:self.selectedHeight]) {
                item_1.state = @"2";
            }
            break;
        } else {
            item_1.state = @"0";
        }
    }
    
}

/** 添加观察者必须要实现的方法 */
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    NSString *new = [change objectForKey:@"new"];
    
    if ([keyPath isEqualToString:@"selectedWidth"]) {
        
        [self changeInputWidth:new];
        
    } else if ([keyPath isEqualToString:@"selectedHeight"]) {
        
        [self changeInputHeight:new];
        
    }
}

- (void)changeInputWidth:(NSString *)new {
    
    CGFloat w = [new intValue] * SJItemWH + ([new intValue] - 1) * SJMargin;
    
    // 开启动画
    [UIView animateWithDuration:.25 animations:^{
        self.inputBGView.sd_layout
        .widthIs(w);
        [self.inputBGView updateLayout];
        [self.cameraButton updateLayout];
        [self.picImageView updateLayout];
        [self.deleteButton updateLayout];
    }];
}

- (void)changeInputHeight:(NSString *)new {
    
    CGFloat h = [new intValue] * SJItemWH + ([new intValue] - 1) * SJMargin;
    
    // 开启动画
    [UIView animateWithDuration:.25 animations:^{
        self.inputBGView.sd_layout
        .heightIs(h);
        [self.inputBGView updateLayout];
        [self.cameraButton updateLayout];
        [self.picImageView updateLayout];
        [self.deleteButton updateLayout];
    }];
    
}

- (void)setupUI {
    
    [self.view addSubview:self.navigationBarView];
    
    if (812 == SJScreenH) {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(40))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    } else {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(0))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    }
    
    [self.view addSubview:self.headerContainView];
    self.headerContainView.sd_layout
    .leftSpaceToView(self.view, SJLayoutFrame(0))
    .topSpaceToView(self.navigationBarView, SJLayoutFrame(0))
    .rightSpaceToView(self.view, SJLayoutFrame(0))
    .heightIs((SJItemWH * 8 + SJMargin * 7) + 2 * SJMargin + SJItemWH);
    
    CGFloat w = SJItemWH * 8 + SJMargin * 7;
    
    [self.headerContainView addSubview:self.titleBGView];
    self.titleBGView.sd_layout
    .centerXEqualToView(self.headerContainView)
    .topSpaceToView(self.headerContainView, SJMargin)
    .heightIs(SJItemWH)
    .widthIs(w);
    
    [self.titleBGView addSubview:self.titleTextView];
    self.titleTextView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(SJLayoutFrame(3), SJLayoutFrame(3), SJLayoutFrame(3), SJLayoutFrame(3)));
    
    CGFloat h = SJItemWH * 2 + SJMargin * 1;
    CGFloat y = (SJItemWH * 8 + SJMargin * 7) / 2 + 2 * SJMargin + SJItemWH;
    
    [self.headerContainView addSubview:self.inputBGView];
    self.inputBGView.sd_layout
    .centerXEqualToView(self.headerContainView)
    .centerYIs(y)
    .heightIs(h)
    .widthIs(h);
    
    [self.inputBGView addSubview:self.cameraButton];
    self.cameraButton.sd_layout
    .centerXEqualToView(self.inputBGView)
    .centerYEqualToView(self.inputBGView)
    .widthIs(SJLayoutFrame(58))
    .heightIs(SJLayoutFrame(53));
    
    [self.view addSubview:self.containView];
    self.containView.sd_layout
    .leftSpaceToView(self.view, SJLayoutFrame(0))
    .topSpaceToView(self.headerContainView, SJLayoutFrame(0))
    .rightSpaceToView(self.view, SJLayoutFrame(0))
    .bottomSpaceToView(self.view, SJLayoutFrame(0));
    
    [self.containView addSubview:self.collectionView];
    self.collectionView.sd_layout
    .leftSpaceToView(self.containView, SJLayoutFrame(20))
    .topSpaceToView(self.containView, SJLayoutFrame(20))
    .heightIs(SJLayoutFrame(148))
    .widthIs(SJScreenW - SJLayoutFrame(40));
    
    UILabel *cpLabel = [UILabel new];
    cpLabel.textColor = SJColorHexString(@"#ffffff");
    cpLabel.font = [UIFont systemFontOfSize:SJLayoutFrame(12)];
    cpLabel.textAlignment = NSTextAlignmentCenter;
    cpLabel.text = @"允许复制";
    cpLabel.numberOfLines = 1;
    
    [self.containView addSubview:cpLabel];
    cpLabel.sd_layout
    .rightSpaceToView(self.containView, SJLayoutFrame(26))
    .topSpaceToView(self.collectionView, SJLayoutFrame(26.5))
    .heightIs(SJLayoutFrame(20));
    [cpLabel setSingleLineAutoResizeWithMaxWidth:180];
    
    [self.containView addSubview:self.cpButton];
    self.cpButton.sd_layout
    .rightSpaceToView(cpLabel, SJLayoutFrame(0))
    .centerYEqualToView(cpLabel)
    .heightIs(SJLayoutFrame(30))
    .widthIs(SJLayoutFrame(30));
    
    [self.inputBGView addSubview:self.picImageView];
    self.picImageView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0));
    
    // scrollview自动contentsize
    [self.containView setupAutoContentSizeWithBottomView:self.cpButton bottomMargin:SJLayoutFrame(30)];
    
}



#pragma mark - getter

- (void)allowCopyAction {
    
    self.cpButton.selected = !self.cpButton.selected;
    if (self.cpButton.selected) {
        self.allowCopy = @"2";
    } else {
        self.allowCopy = @"1";
    }
}

- (UIButton *)cpButton {
    
    if (!_cpButton) {
        
        _cpButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cpButton setImage:[UIImage imageNamed:@"btn_allow_collect_nor"] forState:UIControlStateNormal];
        [_cpButton setImage:[UIImage imageNamed:@"btn_allow_collect_sel"] forState:UIControlStateSelected];
        [_cpButton addTarget:self action:@selector(allowCopyAction) forControlEvents:UIControlEventTouchUpInside];
        _cpButton.selected = YES;
    }
    return _cpButton;
}

- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];
        for (int i = 0; i < 2; i++) {
            
            SJAddItem *item = [SJAddItem new];
            
            if (0 == i) item.numble = @"1:1";
            if (1 == i) item.numble = @"2:2";
            
            item.state = @"1";
            [_dataArray addObject:item];
        }
    }
    return _dataArray;
}


- (UIView *)navigationBarView{
    
    if (!_navigationBarView) {
        
        _navigationBarView = [UIView new];
        _navigationBarView.backgroundColor = [UIColor clearColor];
        
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction)];
        singleTap.cancelsTouchesInView = NO;
        [_navigationBarView addGestureRecognizer:singleTap];
        
        // 返回
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setImage:[UIImage imageNamed:@"addtext-icon-return"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:backButton];
        backButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .leftSpaceToView(_navigationBarView, SJLayoutFrame(10))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(30));
        
        // 词条输入
        UILabel *wordLabel = [UILabel new];
        wordLabel.textColor = SJColorHexString(@"#ffffff");
        wordLabel.font = [UIFont fontWithName:@"Helvetica" size:SJLayoutFrame(17)];
        wordLabel.textAlignment = NSTextAlignmentCenter;
        wordLabel.text = @"编辑音频封面";
        
        [_navigationBarView addSubview:wordLabel];
        wordLabel.sd_layout
        .centerYEqualToView(_navigationBarView)
        .centerXEqualToView(_navigationBarView)
        .heightIs(SJLayoutFrame(27));
        [wordLabel setSingleLineAutoResizeWithMaxWidth:SJScreenW * .5];
        
        // 确定
        UIButton *affirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [affirmButton setImage:[UIImage imageNamed:@"addtext_icon_confirm"] forState:UIControlStateNormal];
        [affirmButton addTarget:self action:@selector(uploadAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:affirmButton];
        affirmButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .rightSpaceToView(_navigationBarView, SJLayoutFrame(20))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(60));
        
    }
    return _navigationBarView;
}

- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (UITextField *)titleTextView {
    
    if (!_titleTextView) {
        
        _titleTextView = [UITextField new];
        _titleTextView.font = [UIFont fontWithName:@"Helvetica-Bold" size:SJLayoutFrame(16)];
        _titleTextView.textColor = SJColorHexString(@"#ffffff");
        _titleTextView.backgroundColor = [UIColor clearColor];
        _titleTextView.textAlignment = NSTextAlignmentLeft;
        _titleTextView.returnKeyType = UIReturnKeyDone;
        
        NSString *holderText = @"请输入标题...";
        NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:holderText];
        [placeholder addAttribute:NSForegroundColorAttributeName
                            value:SJColorHexString(@"#ffffff90")
                            range:NSMakeRange(0, holderText.length)];
        [placeholder addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:SJLayoutFrame(15)]
                            range:NSMakeRange(0, holderText.length)];
        _titleTextView.attributedPlaceholder = placeholder;
        
    }
    return _titleTextView;
}

- (UIView *)titleBGView {
    
    if (!_titleBGView) {
        
        _titleBGView = [UIView new];
        _titleBGView.sd_cornerRadius = @(SJCornerRadius);
        _titleBGView.backgroundColor = SJColorHexString(@"#ffffff19");
    }
    return _titleBGView;
}

- (UIView *)inputBGView {
    
    if (!_inputBGView) {
        
        _inputBGView = [UIView new];
        _inputBGView.sd_cornerRadius = @(SJCornerRadius);
        _inputBGView.backgroundColor = SJColorHexString(@"#ffffff19");
    }
    return _inputBGView;
}

- (UIScrollView *)containView {
    
    if (!_containView) {
        
        _containView = [UIScrollView new];
        _containView.showsVerticalScrollIndicator = NO;
        _containView.showsHorizontalScrollIndicator = NO;
        
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction)];
        singleTap.cancelsTouchesInView = NO;
        [_containView addGestureRecognizer:singleTap];
        
    }
    return _containView;
}

- (void)singleTapAction {
    
    [self.view endEditing:YES];
}

- (UIView *)headerContainView {
    
    if (!_headerContainView) {
        
        _headerContainView = [UIView new];
        
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction)];
        singleTap.cancelsTouchesInView = NO;
        [_headerContainView addGestureRecognizer:singleTap];
        
    }
    return _headerContainView;
}


- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat h = SJLayoutFrame(22);
        CGFloat w = SJLayoutFrame(52);
        layout.minimumInteritemSpacing = SJLayoutFrame(40);
        layout.minimumLineSpacing = SJLayoutFrame(20);
        layout.itemSize = CGSizeMake(w, h);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        
        [_collectionView registerClass:[SJAddWHCell class] forCellWithReuseIdentifier:NSStringFromClass([SJAddWHCell class])];
        
    }
    
    return _collectionView;
}


- (void)deleteAction {
    
    self.picImageView.hidden = YES;
    self.uploadImage = nil;
    
}

- (UIButton *)deleteButton{
    
    if (!_deleteButton) {
        
        _deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_deleteButton addTarget:self action:@selector(deleteAction) forControlEvents:UIControlEventTouchUpInside];
        [_deleteButton setImage:[UIImage imageNamed:@"addpic_icon_delete"] forState:UIControlStateNormal];
        
    }
    return _deleteButton;
}

- (UIImageView *)picImageView {
    
    if (!_picImageView) {
        _picImageView = [UIImageView new];
        _picImageView.contentMode = UIViewContentModeScaleAspectFill;
        _picImageView.userInteractionEnabled = YES;
        _picImageView.sd_cornerRadius = @(SJLayoutFrame(6));
        
        [_picImageView addSubview:self.deleteButton];
        self.deleteButton.sd_layout
        .topSpaceToView(_picImageView, SJLayoutFrame(6))
        .rightSpaceToView(_picImageView, SJLayoutFrame(6))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(30));
        
    }
    return _picImageView;
}

- (UIButton *)cameraButton{
    
    if (!_cameraButton) {
        
        _cameraButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cameraButton addTarget:self action:@selector(cameraAction) forControlEvents:UIControlEventTouchUpInside];
        [_cameraButton setBackgroundImage:[UIImage imageNamed:@"upload_btn_photo"] forState:UIControlStateNormal];
        
    }
    return _cameraButton;
}

- (void)cameraAction { // 进入相册
    
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    
    //以下参数为自定义参数，均可不设置，有默认值
    actionSheet.configuration.allowSelectImage = YES;
    actionSheet.configuration.allowSelectGif = NO;
    actionSheet.configuration.allowSelectVideo = NO;
    actionSheet.configuration.allowSelectLivePhoto = YES;
    actionSheet.configuration.allowForceTouch = NO;
    actionSheet.configuration.allowEditImage = YES;
    actionSheet.configuration.allowEditVideo = YES;
    actionSheet.configuration.allowSlideSelect = NO;
    actionSheet.configuration.allowMixSelect = NO;
    //设置相册内部显示拍照按钮
    actionSheet.configuration.allowTakePhotoInLibrary = YES;
    //设置在内部拍照按钮上实时显示相机俘获画面
    actionSheet.configuration.showCaptureImageOnTakePhotoBtn = YES;
    //设置照片最大预览数
    actionSheet.configuration.maxPreviewCount = 0;
    //设置照片最大选择数
    actionSheet.configuration.maxSelectCount = 1;
    //单选模式是否显示选择按钮
    actionSheet.configuration.showSelectBtn = NO;
    actionSheet.configuration.saveNewImageAfterEdit = NO;
    //是否在选择图片后直接进入编辑界面
    actionSheet.configuration.editAfterSelectThumbnailImage = YES;
    actionSheet.configuration.navBarColor = SJColorHexString(@"#00000090");
    actionSheet.configuration.bottomViewBgColor = SJColorHexString(@"#00000090");
    //设置编辑比例
    //    actionSheet.clipRatios = @[GetClipRatio(4, 3)];
    WeakSelf;
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        //
        //        [weakSelf.inputBGView addSubview:weakSelf.picImageView];
        //        weakSelf.picImageView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0));
        weakSelf.picImageView.image = [images lastObject];
        weakSelf.uploadImage = [images lastObject];
        weakSelf.picImageView.hidden = NO;
    }];
    
    //调用相册
    [actionSheet showPhotoLibraryWithSender:self];
    
}

/**
 七牛
 */
- (QNUploadManager *)upManager{
    
    if (!_upManager) {
        //华北
        QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) {
            builder.zone = [QNFixedZone zone1];
        }];
        _upManager = [[QNUploadManager alloc] initWithConfiguration:config];
    }
    return _upManager;
}

//照片获取本地路径转换
- (NSString *)getImagePath:(UIImage *)Image {
    
    NSString *filePath = nil;
    NSData *data = nil;
    
    data = [UIImage dataCompressImageQuality:Image toByte:200 * 1024];
    
    //图片保存的路径
    //这里将图片放在沙盒的documents文件夹中
    NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //把刚刚图片转换的data对象拷贝至沙盒中
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *ImagePath = [[NSString alloc] initWithFormat:@"/userHeader.png"];
    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:ImagePath] contents:data attributes:nil];
    
    //得到选择后沙盒中图片的完整路径
    filePath = [[NSString alloc] initWithFormat:@"%@%@", DocumentsPath, ImagePath];
    return filePath;
}

/**
 上传七牛
 
 @param filePath 图片路径
 */
- (void)uploadImageToQNFilePath:(NSString *)filePath {
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
    [SVProgressHUD showWithStatus:@"正在上传..."];
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"type"] = @"1";
    
    SJGetUpTokenApi *api = [[SJGetUpTokenApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            NSString *uploadToken = [NSString stringWithFormat:@"%@",api.responseObject[@"content"][@"uptoken"]];
            NSString *key = [NSString stringWithFormat:@"%@",api.responseObject[@"content"][@"key"]];
            [self.upManager putFile:filePath key:key token:uploadToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                
                if (info.isOK) {
                    // 上传自己服务器
                    [self updatePic:key];
                } else {
                    
                    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
                    [SVProgressHUD showErrorWithStatus:@"上传失败"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                    });
                }
            } option:nil];
            
        } else {
            
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
            [SVProgressHUD showErrorWithStatus:@"上传失败"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            
        }
        
    } failure:^(YTKBaseRequest *request) {
    }];
}

- (void)updatePic:(NSString *)key {
    
    if ([self.titleTextView.text length] > 21) { // 最多21个字
        [SVProgressHUD showInfoWithStatus:@"最多21个字符"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"format"] = @"3";
    parameters[@"cover"] = key;
    
    if ([self.titleTextView.text isNotBlank]) {
        parameters[@"title"] = self.titleTextView.text;
    }
    
    parameters[@"l"] = self.item.l;
    parameters[@"t"] = self.item.t;
    parameters[@"w"] = self.selectedWidth;
    parameters[@"h"] = self.selectedHeight;
    
    parameters[@"id"] = self.item.ID;
    parameters[@"can_fav"] = self.allowCopy;
    
    SJModifyMediaApi *api = [[SJModifyMediaApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            SJWordItem *item = [SJWordItem modelWithJSON:api.responseObject[@"content"]];
            item.is_me = @"1";
            //            item.fmt = self.item.fmt;
            
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            
            [[NSNotificationCenter defaultCenter] postNotificationName:SJDidEditWordNotification object:nil userInfo:@{@"item": item}];
            [self.navigationController popViewControllerAnimated:YES];
            
        } else {
            
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
            [SVProgressHUD showErrorWithStatus:@"上传失败"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            
        }
        
    } failure:^(YTKBaseRequest *request) {
    }];
}


- (void)uploadAction {
    
    if (!self.uploadImage) {
        
        SJExtraItem *extraItem = [SJExtraItem modelWithJSON:self.item.extra];
        
        [self updatePic:extraItem.cover];
        return;
    }
    
    [self.view endEditing:YES];
    
    [self uploadImageToQNFilePath:[self getImagePath:self.uploadImage]];
}


#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJAddWHCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SJAddWHCell class]) forIndexPath:indexPath];
    SJAddItem *item = self.dataArray[indexPath.item];
    cell.item = item;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    for (SJAddItem *item in self.dataArray) {
        if ([item.state isEqualToString:@"2"]) {
            item.state = @"1";
        }
    }
    
    SJAddItem *item = self.dataArray[indexPath.item];
    if ([item.state isEqualToString:@"0"]) {
        return;
    }
    item.state = @"2";
    [self.collectionView reloadData];
    
    NSArray *WHArray = [item.numble componentsSeparatedByString:@":"];
    
    self.selectedHeight = [NSString stringWithFormat:@"%ld", [WHArray[0] integerValue] * 2];
    self.selectedWidth = [NSString stringWithFormat:@"%ld", [WHArray[1] integerValue] * 2];
}

@end
